<template>
  <div class="tinymce-container editor-container">
    <textarea class="tinymce-textarea" :id="tinymceId"></textarea>
    <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK"></editorImage>
    </div>
  </div>
</template>

<script>
import editorImage from './components/editorImage'
import plugins from './plugins'
import toolbar from './toolbar'

export default {
  name: 'tinymce',
  components: { editorImage },
  props: {
    tid: {
      type: String,
      default: ''
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    isPlugin: {
      type: Number,
      default: 0
    },
    menubar: {
      default: 'file edit insert view table'
    },
    emptyMenubar: {
      default: ''
    },
    height: {
      type: Number,
      required: false,
      default: 360
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.tid || 'vue-tinymce-' + +new Date()
    }
  },
  watch: {
    value(val) {
      // console.log('编辑器：', this.tinymceId, val)
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(val))
      }
    }
  },
  mounted() {
    if (this.isPlugin == 0) {
      this.initTinymce()
    } else {
      this.initTinymceNoPlugins()
      // document.querySelector('#mceu_23').style.display = 'none'
    }
    // console.log('编辑器mounted：', this.tinymceId,this.value)
    // if (!this.hasChange && this.hasInit) {
    //   this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(this.value))
    // }
  },
  activated() {
    this.initTinymce()
  },
  deactivated() {
    this.destroyTinymce()
  },
  methods: {
    initTinymce() {
      const _this = this
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        language: 'zh_CN',
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',

        // CONFIG

        forced_root_block: 'p',
        force_p_newlines: true,
        importcss_append: true,

        // CONFIG: ContentStyle 这块很重要， 在最后呈现的页面也要写入这个基本样式保证前后一致， `table`和`img`的问题基本就靠这个来填坑了
        content_style: `
            *                         { padding:0; margin:0; }
            html, body                { height:100%; }
            img                       { max-width:100%; display:block;height:auto; }
            a                         { text-decoration: none; }
            iframe                    { width: 100%; }
            p                         { line-height:1.6; margin: 0px; }
            table                     { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
            .mce-object-iframe        { width:100%; box-sizing:border-box; margin:0; padding:0; }
            ul,ol                     { list-style-position:inside; }
          `,

        insert_button_items: 'image link | inserttable',
        paste_retain_style_properties: 'all',
        paste_word_valid_elements: '*[*]', // word需要它
        paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
        paste_convert_word_fake_lists: true, // 插入word文档需要该属性
        paste_webkit_styles: 'all',
        paste_merge_formats: true,
        nonbreaking_force_tab: false,
        paste_auto_cleanup_on_paste: false,

        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        style_formats: [
          {
            title: '首行缩进',
            block: 'p',
            styles: { 'text-indent': '2em' }
          },
          {
            title: '行高',
            items: [
              { title: '1', styles: { 'line-height': '1' }, inline: 'span' },
              { title: '1.5', styles: { 'line-height': '1.5' }, inline: 'span' },
              { title: '2', styles: { 'line-height': '2' }, inline: 'span' },
              { title: '2.5', styles: { 'line-height': '2.5' }, inline: 'span' },
              { title: '3', styles: { 'line-height': '3' }, inline: 'span' }
            ]
          },
          {
            title: '字号',
            items: [
              { title: '10px', styles: { 'font-size': '10px' }, inline: 'span' },
              { title: '12px', styles: { 'font-size': '12px' }, inline: 'span' },
              { title: '14px', styles: { 'font-size': '14px' }, inline: 'span' },
              { title: '16px', styles: { 'font-size': '16px' }, inline: 'span' },
              { title: '18px', styles: { 'font-size': '18px' }, inline: 'span' },
              { title: '20px', styles: { 'font-size': '20px' }, inline: 'span' },
              { title: '22px', styles: { 'font-size': '22px' }, inline: 'span' },
              { title: '24px', styles: { 'font-size': '24px' }, inline: 'span' },
              { title: '26px', styles: { 'font-size': '26px' }, inline: 'span' },
              { title: '28px', styles: { 'font-size': '28px' }, inline: 'span' },
              { title: '30px', styles: { 'font-size': '30px' }, inline: 'span' },
              { title: '32px', styles: { 'font-size': '32px' }, inline: 'span' },
              { title: '34px', styles: { 'font-size': '34px' }, inline: 'span' },
              { title: '36px', styles: { 'font-size': '36px' }, inline: 'span' },
              { title: '38px', styles: { 'font-size': '38px' }, inline: 'span' },
              { title: '40px', styles: { 'font-size': '40px' }, inline: 'span' }
            ]
          },
          {
            title: '字体',
            items: [
              { title: '微软雅黑', styles: { 'font-family': '微软雅黑' }, inline: 'span' },
              { title: '宋体', styles: { 'font-family': '宋体' }, inline: 'span' },
              { title: '黑体', styles: { 'font-family': '黑体' }, inline: 'span' },
              { title: '仿宋', styles: { 'font-family': '仿宋' }, inline: 'span' },
              { title: '楷体', styles: { 'font-family': '楷体' }, inline: 'span' },
              { title: '隶书', styles: { 'font-family': '隶书' }, inline: 'span' },
              { title: '幼圆', styles: { 'font-family': '幼圆' }, inline: 'span' },
              { title: 'Andale Mono', styles: { 'font-family': 'Andale Mono,times' }, inline: 'span' },
              { title: 'Arial', styles: { 'font-family': 'arial, helvetica,sans-serif' }, inline: 'span' },
              { title: 'Arial Black', styles: { 'font-family': 'arial black, avant garde' }, inline: 'span' },
              { title: 'Book Antiqua', styles: { 'font-family': 'book antiqua,palatino' }, inline: 'span' },
              { title: 'Comic Sans MS', styles: { 'font-family': 'comic sans ms,sans-serif' }, inline: 'span' },
              { title: 'Courier New', styles: { 'font-family': 'courier new,courier' }, inline: 'span' },
              { title: 'Georgia', styles: { 'font-family': 'georgia,palatino' }, inline: 'span' },
              { title: 'Helvetica', styles: { 'font-family': 'helvetica' }, inline: 'span' },
              { title: 'Impact', styles: { 'font-family': 'impact,chicago' }, inline: 'span' },
              { title: 'Symbol', styles: { 'font-family': 'symbol' }, inline: 'span' },
              { title: 'Tahoma', styles: { 'font-family': 'tahoma,arial,helvetica,sans-serif' }, inline: 'span' },
              { title: 'Terminal', styles: { 'font-family': 'terminal,monaco' }, inline: 'span' }
            ]
          }
        ],
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        }
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img);
        //     $image.removeAttr('width');
        //     $image.removeAttr('height');
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr('data-wscntype', 'image');
        //       $image.attr('data-wscnh', $image[0].height);
        //       $image.attr('data-wscnw', $image[0].width);
        //       $image.addClass('wscnph');
        //     }
        //   }, 0);
        //   return img
        // },
        // images_upload_handler(blobInfo, success, failure, progress) {
        //   progress(0);
        //   const token = _this.$store.getters.token;
        //   getToken(token).then(response => {
        //     const url = response.data.qiniu_url;
        //     const formData = new FormData();
        //     formData.append('token', response.data.qiniu_token);
        //     formData.append('key', response.data.qiniu_key);
        //     formData.append('file', blobInfo.blob(), url);
        //     upload(formData).then(() => {
        //       success(url);
        //       progress(100);
        //     })
        //   }).catch(err => {
        //     failure('出现未知问题，刷新页面，或者联系程序员')
        //     console.log(err);
        //   });
        // },
      })
    },
    initTinymceNoPlugins() {
      const _this = this
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        menubar: this.emptyMenubar,
        language: 'zh_CN',
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        }
      })
    },
    destroyTinymce() {
      if (window.tinymce.get(this.tinymceId)) {
        window.tinymce.get(this.tinymceId).destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      const _this = this
      arr.forEach(v => {
        window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
      })
    }
  },
  destroyed() {
    this.destroyTinymce()
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
}
.tinymce-container>>>.mce-fullscreen {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.editor-upload-btn {
  display: inline-block;
}
</style>
